package com.link.base.base.sms.service;

import com.link.base.sms.model.*;
import com.link.base.base.user.model.User;
import com.link.base.base.coupons.model.Coupons;
import com.link.base.base.coupons.service.CouponsService;
import com.link.base.base.opty.model.Opty;
import com.link.base.base.sms.dao.mybatis.mapper.PushSmsMapper;
import com.link.base.base.sms.dao.mybatis.mapper.SmsSendMapper;
import com.link.base.base.sms.dao.mybatis.mapper.TemparameterMapper;
import com.link.base.base.sms.model.PushSms;
import com.link.base.base.user.service.UserService;
import com.link.base.base.wechat.model.WxTemplate;
import com.link.base.base.wechat.service.WxTemplateService;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.interceptor.SecurityInterceptor;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.Filter;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.ServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.util.DateUtil;
import com.link.core.util.PropertyUtil;
import com.link.core.util.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: liulu
 * @Date:15:37 2018/11/5
 */
@Service
public class PushSmsServiceImpl extends BasicServiceImpl<PushSms> implements PushSmsService {

    @Resource
    private PushSmsMapper pushSmsMapper;
    @Resource
    private SmsSendMapper smsSendMapper;
    @Resource
    private TemparameterMapper temparameterMapper;
    @Resource
    private CouponsService couponsService;
    @Resource
    private TemplateService templateService;
    @Resource
    private SignatureService signatureService;
    @Resource
    private SmsSendService smsSendService;
    @Resource
    private SmsAccntLineService smsAccntLineService;
    @Resource
    private WxTemplateService wxTemplateService;
    @Resource
    private UserService userService;

    public static int daysBetween(Date date1, Date date2) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date1);
        long time1 = cal.getTimeInMillis();
        cal.setTime(date2);
        long time2 = cal.getTimeInMillis();
        long betweenDays = (time2 - time1) / (1000 * 3600 * 24);

        return Integer.parseInt(String.valueOf(betweenDays));
    }

    @Override
    public BasicMapper<PushSms> getBasicMapper() {
        return pushSmsMapper;
    }

    /**
     * 一天扫描一次，发送短信
     */
    @Override
    public void oneDayPushSendSms() {
        PushSms push = new PushSms();
        try {
            push.setPushSwitch("Y");
            List<PushSms> pushSmsList = pushSmsMapper.queryAll(push);
            for (PushSms arr : pushSmsList) {
                switch (arr.getType()) {
                    default:
                        break;
                    //发送生日短信
                    case "birthday":
                        this.isBirthday(arr.getTemId(), arr.getLoginCorpId());
                        break;
                    //优惠券过期短信
                    case "coupon":
                        this.couponIsExpireSms(arr.getTemId(), arr.getLoginCorpId());
                }

            }

        } catch (Exception e) {
            LCLogger.withException(e);
        }

    }

    /**
     * 一天扫描一次，发送生日祝贺
     */
    public void isBirthday(Long birthdayTemId, Long cropId) {
        //生日模板ID
        SmsAccntLine accnt = new SmsAccntLine();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        try {
            accnt.setLoginCorpId(cropId);
            List<SmsAccntLine> listsrr = pushSmsMapper.queryByBirthday(accnt);
            List<SmsAccntLine> list = new ArrayList<>();
            list = smsAccntLineService.addlist(list, listsrr);
            Signature sige = new Signature();
            sige.setCorpid(cropId);
            sige.setTotalFlag(false);
            sige.setDefaultdFlag("Y");
            List<Signature> signaturelist = signatureService.queryByExamplePage(sige);
            for (SmsAccntLine accn : list) {
                SmsSend send = new SmsSend();
                send.setLoginCorpId(cropId);
                send.setSendTime(sdf.format(new Date()));
                send.setId(keyGenerateService.keyGenerate());
                send.setSendPeopleCount(1);
                send.setSendState("New");
                //把客户与短信关联
                smsSendService.addSendAccontLine(send.getId(), accn.getId());
                send.setSignatureId(signaturelist.get(0).getId());
                send.setSigText(signaturelist.get(0).getText());
                send.setTemplateId(birthdayTemId);
                //插入模板参数
                Temparameter temparameter = new Temparameter();
                temparameter.setId(keyGenerateService.keyGenerate());
                temparameter.setTemId(birthdayTemId);
                temparameter.setParameter1(signaturelist.get(0).getText());
                temparameterMapper.insert(temparameter);
                send.setTemparameterId(temparameter.getId());
                smsSendMapper.insert(send);
                smsSendService.sendSms(send);

            }

        } catch (Exception e) {
            LCLogger.withException(e);
        }

    }

    /**
     * 接待记录10分钟扫描一次
     */
    public void isReception2(Long receptionTemId, Long cropId) {
        //接待模板ID
        SmsAccntLine accnt = new SmsAccntLine();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date date1 = new Date();

        long time = (date1.getTime() / 1000) - 60 * 30;
        date1.setTime(time * 1000);
        String startDate = format.format(date1);
        Date date2 = new Date();
        long time2 = (date2.getTime() / 1000) - 60 * 20;
        date2.setTime(time2 * 1000);
        String endDate = format.format(date2);
        try {
            Map<String, String> map = new HashMap(8);
            map.put("start", startDate);
            map.put("end", endDate);
            map.put("loginCorpId", accnt.getLoginCorpId().toString());
            List<Opty> list = pushSmsMapper.queryByreception(map);
            for (Opty accn : list) {
                SmsSend send = new SmsSend();
                send.setLoginCorpId(cropId);
                send.setSendTime(format.format(new Date()));
                send.setId(keyGenerateService.keyGenerate());
                send.setSendPeopleCount(1);
                send.setSendState("New");
                //把客户与短信关联
                smsSendService.addSendAccontLine(send.getId(), accn.getAccntId());
                Signature sige = new Signature();
                sige.setTotalFlag(false);
                sige.setDefaultdFlag("Y");
                List<Signature> signaturelist = signatureService.queryByExamplePage(sige);
                send.setSignatureId(signaturelist.get(0).getId());
                send.setTemplateId(receptionTemId);
                send.setSigText(signaturelist.get(0).getText());
                //插入模板参数
                Temparameter temparameter = new Temparameter();
                temparameter.setId(keyGenerateService.keyGenerate());
                temparameter.setTemId(receptionTemId);
                temparameter.setParameter1(accn.getAccnt());
                temparameterMapper.insert(temparameter);
                send.setTemparameterId(temparameter.getId());
                smsSendMapper.insert(send);

                smsSendService.sendSms(send);

            }
        } catch (Exception e) {
            LCLogger.withException(e);
        }

    }

    /**
     * 优惠卷过期记录，一天查一次f
     */
    public void couponIsExpireSms(Long couponsTemId, Long cropId) {
        //优惠卷模板ID
        Coupons coupons = new Coupons();
        QueryParams qps = new QueryParams();
        qps.setPageFlag(false);

        qps.addFilter(new Filter("effectEndTime", Filter.OP_LESS_EQUAL, this.setTime(3)));

        qps.addFilter(new Filter("effectEndTime", Filter.OP_GREAT_THEN, this.setTime(2)));
        Coupons a = (Coupons) BasicModel.transformClass(coupons, qps);
        try {
            a.setLoginCorpId(cropId);
            Signature sige = new Signature();
            sige.setLoginCorpId(cropId);
            sige.setTotalFlag(false);
            sige.setDefaultdFlag("Y");

            List<Coupons> coun = couponsService.queryByExamplePage(a);
            List<Signature> signaturelist = signatureService.queryByExamplePage(sige);
//查出默认模板
            for (Coupons accn : coun) {
                SmsSend send = new SmsSend();
                send.setLoginCorpId(cropId);
                send.setId(keyGenerateService.keyGenerate());
                send.setSendPeopleCount(1);
                send.setSendState("New");
//把客户与短信关联
                smsSendService.addSendAccontLine(send.getId(), accn.getAccntId());
                send.setSignatureId(signaturelist.get(0).getId());
                send.setSigText(signaturelist.get(0).getText());
                send.setTemplateId(couponsTemId);
                //插入模板参数
                Temparameter temparameter = new Temparameter();
                temparameter.setId(keyGenerateService.keyGenerate());
                temparameter.setTemId(couponsTemId);
                temparameter.setParameter1(accn.getCouponsName());
                temparameter.setParameter2(accn.getUrl1());
                temparameterMapper.insert(temparameter);
                send.setTemparameterId(temparameter.getId());
                smsSendMapper.insert(send);
                smsSendService.sendSms(send);

            }
        } catch (Exception e) {
            LCLogger.withException(e);
        }

    }


    public String setTime(int time) {
        String str = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar lastDate = Calendar.getInstance();
        lastDate.add(Calendar.DATE, +time);
        str = sdf.format(lastDate.getTime());
        return str;
    }

    /**
     * 客户ID：accoutId
     * 优惠券名：DiscountCouponname
     * 链接：url
     *
     * @return
     */
    @Override
    public void pullDiscountCouponSendSms(String prizeType, Long accoutId, String discountCouponname, String url, Long corpid) {
        Long couponTemId;
        String coupon = "Coupon";
        if (coupon.equals(prizeType)) {
            couponTemId = Long.parseLong(PropertyUtil.getProperty("pullDiscountCouponTemId", corpid));
        } else {
            couponTemId = Long.parseLong(PropertyUtil.getProperty("prizenameTemId", corpid));
        }
        Temparameter temparameter = new Temparameter();
        temparameter.setTemId(couponTemId);
        temparameter.setParameter1(discountCouponname);
        temparameter.setParameter2(url);
        String time = DateUtil.dateToStr(new Date(), "yyyy-MM-dd hh:mm:ss");
        temparameter.setCorpid(corpid);
        try {
            this.pushSendSms(temparameter, accoutId, "Imidiately", time);
        } catch (Exception e) {
            LCLogger.withException(e);
        }

    }

    /**
     * 客户ID：acctId
     * 客户名称：acctName
     * 门店名称：shopName
     * 门店电话
     * 客户访问发送短信
     *
     * @return
     */
    public void isReception(Long acctId, String acctName, String shopName, String shopPhone) {
        PushSms push = new PushSms();
        push.setPageFlag(false);
        push.setType("visit");
        try {
            String flag = "Y";
            List<PushSms> pushList = pushSmsMapper.queryByExamplePage(push);
            if (StringUtils.equals(pushList.get(0).getPushSwitch(), flag)) {
                Long temId = pushList.get(0).getTemId();
                Temparameter temparameter = new Temparameter();
                temparameter.setTemId(temId);
                temparameter.setParameter1(acctName);
                temparameter.setParameter2(shopName);
                temparameter.setParameter3(shopPhone);
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                Date date1 = new Date();
                long timeLong = (date1.getTime() / 1000) - 60 * 30;
                date1.setTime(timeLong * 1000);
                String time = format.format(date1);
                this.pushSendSms(temparameter, acctId, "Imidiately", time);
            }
        } catch (Exception e) {
            LCLogger.withException(e);
        }
    }

    /**
     * @Author:LiuLu
     * @params: 客户id
     * @params: 客户名称
     * @params: 门店名称
     * @params: 总金额
     * @return:
     * @Date:16:32 2018/5/17
     * @zhu:提交订单发送短信
     */

    @Override
    public void submitOrderSendSms(Long acctId, String acctName, String shopName, String orderMoney, Long saleOrderId) {
        PushSms push = new PushSms();
        push.setPageFlag(false);
        push.setType("submitOrder");
        try {
            String flag = "Y";
            List<PushSms> pushList = pushSmsMapper.queryByExamplePage(push);
            if (StringUtils.equals(pushList.get(0).getPushSwitch(), flag)) {
                Long temId = pushList.get(0).getTemId();
                Temparameter temparameter = new Temparameter();
                temparameter.setTemId(temId);
                temparameter.setParameter1(acctName);
                temparameter.setParameter2(shopName);
                temparameter.setParameter3(orderMoney);
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                String time = format.format(new Date());
                this.pushSendSms(temparameter, acctId, "Imidiately", time);

            }
            if (StringUtils.equals(pushList.get(0).getWxOpenFlag(), flag)) {
                Calendar endcalendar = Calendar.getInstance();
                endcalendar.add(Calendar.MINUTE, 30);
                String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endcalendar.getTime());
                WxTemplate template = new WxTemplate();
                template.setAcctId(acctId);
                template.setSaleOrderId(saleOrderId);
                template.setTime(time);
                template.setTemplateId(pushList.get(0).getWxTempId());
                wxTemplateService.insert(template);
            }
        } catch (Exception e) {
            LCLogger.withException(e);
        }

    }

    /**
     * @params: 客户id
     * @params: 客户名称
     * @params: 门店名称
     * @return:
     * @Author:LiuLu
     * @Date:16:32 2018/5/17
     * @zhu:订单发货发送短信
     */
    @Override
    public void orderDeliverySendSms(Long acctId, String acctName, String shopName, Long saleOrderId) {
        PushSms push = new PushSms();
        push.setPageFlag(false);
        push.setType("orderDelivery");
        try {
            String flag = "Y";
            List<PushSms> pushList = pushSmsMapper.queryByExamplePage(push);
            if (StringUtils.equals(pushList.get(0).getPushSwitch(), flag)) {
                Long temId = pushList.get(0).getTemId();
                Temparameter temparameter = new Temparameter();
                temparameter.setTemId(temId);
                temparameter.setParameter1(acctName);
                temparameter.setParameter2(shopName);
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                String time = format.format(new Date());
                this.pushSendSms(temparameter, acctId, "Imidiately", time);
            }
            if (StringUtils.equals(pushList.get(0).getWxOpenFlag(), flag)) {
                Calendar endcalendar = Calendar.getInstance();
                endcalendar.add(Calendar.MINUTE, 30);
                String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endcalendar.getTime());
                WxTemplate template = new WxTemplate();
                template.setAcctId(acctId);
                template.setSaleOrderId(saleOrderId);
                template.setTime(time);
                template.setTemplateId(pushList.get(0).getWxTempId());
                wxTemplateService.insert(template);
            }
        } catch (Exception e) {
            LCLogger.withException(e);
        }
    }

    /**
     * @params: 客户id
     * @params: 客户名称
     * @params: 门店名称
     * @return:
     * @Author:LiuLu
     * @Date:16:32 2018/5/17
     * @zhu:完成订单发送短信
     */
    @Override
    public void finalizeOrderSendSms(Long acctId, String acctName, String shopName, Long saleOrderId) {
        PushSms push = new PushSms();
        push.setPageFlag(false);
        push.setType("finalizeOrder");
        try {
            String flag = "Y";
            List<PushSms> pushList = pushSmsMapper.queryByExamplePage(push);
            if (StringUtils.equals(pushList.get(0).getPushSwitch(), flag)) {
                Long temId = pushList.get(0).getTemId();
                Temparameter temparameter = new Temparameter();
                temparameter.setTemId(temId);
                temparameter.setParameter1(acctName);
                temparameter.setParameter2(shopName);
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                String time = format.format(new Date());
                this.pushSendSms(temparameter, acctId, "Imidiately", time);
            }
            if (StringUtils.equals(pushList.get(0).getWxOpenFlag(), flag)) {
                Calendar endcalendar = Calendar.getInstance();
                endcalendar.add(Calendar.MINUTE, 30);
                String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endcalendar.getTime());
                WxTemplate template = new WxTemplate();
                template.setAcctId(acctId);
                template.setSaleOrderId(saleOrderId);
                template.setTime(time);
                template.setTemplateId(pushList.get(0).getWxTempId());
                wxTemplateService.insert(template);
            }
        } catch (Exception e) {
            LCLogger.withException(e);
        }
    }

    /**
     * @params: 客户id
     * @params: 客户名称
     * @params: 门店名称
     * @return:
     * @Author:LiuLu
     * @Date:16:32 2018/5/17
     * @zhu:取消订单发送短信
     */
    @Override
    public void cancelOrderSendSms(Long acctId, String acctName, String shopName, Long saleOrderId) {
        PushSms push = new PushSms();
        push.setPageFlag(false);
        push.setType("cancelOrder");
        try {
            String flag = "Y";
            List<PushSms> pushList = pushSmsMapper.queryByExamplePage(push);
            if (StringUtils.equals(pushList.get(0).getPushSwitch(), flag)) {
                Long temId = pushList.get(0).getTemId();
                Temparameter temparameter = new Temparameter();
                temparameter.setTemId(temId);
                temparameter.setParameter1(acctName);
                temparameter.setParameter2(shopName);
                String time = DateUtil.dateToStr(new Date(), "yyyy-MM-dd hh:mm:ss");
                this.pushSendSms(temparameter, acctId, "Imidiately", time);
            }
            if (StringUtils.equals(pushList.get(0).getWxOpenFlag(), flag)) {
                Calendar endcalendar = Calendar.getInstance();
                endcalendar.add(Calendar.MINUTE, 30);
                String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endcalendar.getTime());
                WxTemplate template = new WxTemplate();
                template.setAcctId(acctId);
                template.setSaleOrderId(saleOrderId);
                template.setTime(time);
                template.setTemplateId(pushList.get(0).getWxTempId());
                wxTemplateService.insert(template);
            }
        } catch (Exception e) {
            LCLogger.withException(e);
        }
    }

    /**
     * DESC:【场景通知】发送消息公共方法 （暂无小程序消息）
     *
     * @param acctId       客户id
     * @param temparameter 参数列表
     * @param objId        发送消息对象的did
     * @param type         场景通知类型
     * @author: xubowen
     * @return: void
     * @date: 2019-04-17 10:05
     */
    @Override
    public void sceneNotificationSendSms(Long acctId, Temparameter temparameter, Long objId, String type) throws Exception {
        PushSms push = new PushSms();
        push.setPageFlag(false);
        push.setType(type);
        //switch为有效的标记
        String flag = "Y";
        List<PushSms> pushList = pushSmsMapper.queryByExamplePage(push);

        //发送短信消息
        for (PushSms pushSms : pushList) {
            if (null != pushSms.getTemId() && StringUtils.equals(pushSms.getPushSwitch(), flag)) {
                Long temId = pushSms.getTemId();
                temparameter.setTemId(temId);
                String time = DateUtil.dateToStr(new Date(), "yyyy-MM-dd hh:mm:ss");
                this.pushSendSms(temparameter, acctId, "Imidiately", time);
                break;
            }
        }

        //发送微信消息
        for (PushSms pushSms : pushList) {
            if (null != pushSms.getWxTempId() && StringUtils.equals(pushSms.getWxOpenFlag(), flag)) {
                Calendar endcalendar = Calendar.getInstance();
                endcalendar.add(Calendar.MINUTE, 30);
                String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endcalendar.getTime());
                WxTemplate template = new WxTemplate();
                template.setAcctId(acctId);
                template.setSaleOrderId(objId);
                template.setTime(time);
                template.setTemplateId(pushSms.getWxTempId());
                wxTemplateService.insert(template);
                break;
            }
        }
    }

    /**
     * 根据type,获取消息通知信息
     *
     * @param type 消息推送场景类型
     * @return 返回查询到的消息推送信息
     * @throws Exception 异常信息
     * @author 闫有霞
     * @date 2018/12/12
     */

    @Override
    public PushSms queryPushSmsByType(String type) throws Exception {
        // 调用分页查询
        PushSms entity = new PushSms();
        entity.setType(type);
        List<PushSms> list = queryByExamplePage(entity);
        PushSms result = null;
        // 获取第一个查到的配置信息,默认情况下是不允许出现多个配置使用相同的type
        if (list != null && list.size() > 0) {
            result = list.get(0);
        } else {
            throw new ServiceException("SMS-002");
        }
        return result;
    }


    public String pushSendSms(Temparameter temparameter, Long accoutId, String sendMode, String time) throws
            Exception {
        Long corpid = temparameter.getCorpid();
        User user = userService.queryUserByCropId(temparameter.getCorpid());
        SecurityInterceptor.tempUser.set(user);
        Long temid = temparameter.getTemId();
        SmsSend send = new SmsSend();
        send.setSendMode(sendMode);
        send.setId(keyGenerateService.keyGenerate());
        send.setSendPeopleCount(1);
        send.setSendState("New");
        send.setSendTime(time);
        //把客户与短信关联
        try {
            smsSendService.addSendAccontLineNew(send.getId(), accoutId, corpid);
            Template t = new Template();
            t.setCorpid(corpid);
            t.setLoginCorpId(corpid);
            t.setId(temid);
            //查出默认模板
            Template tem = templateService.queryById(t);
            send.setTemplate(tem);
            Signature sige = new Signature();
            sige.setPageFlag(false);
            sige.setDefaultdFlag("Y");
            sige.setCorpid(corpid);
            sige.setLoginCorpId(corpid);
            List<Signature> signaturelist = signatureService.queryByExamplePage(sige);
            send.setSignatureId(signaturelist.get(0).getId());
            send.setSigText(signaturelist.get(0).getText());
            send.setTemplateId(temid);
            send.setCorpid(corpid);
            temparameter.setPostnId(user.getPostnId());
            temparameter.setOrgId(user.getOrgId());
            //插入模板参数
            temparameter.setId(keyGenerateService.keyGenerate());
            temparameterMapper.insert(temparameter);
            send.setTemparameterId(temparameter.getId());
            send.setPostnId(user.getPostnId());
            send.setOrgId(user.getOrgId());
            send.setCorpid(corpid);
            smsSendMapper.insert(send);
            String imidiately = "Imidiately";
            if (imidiately.equals(send.getSendMode())) {
                smsSendService.sendSms(send);
            }
        } catch (Exception e) {
            LCLogger.withException(e);
        }
        return "发送成功";
    }

    @Override
    public PushSms queryByTitle(String sceneName) throws Exception {
        PushSms pushSms = new PushSms();
        pushSms.setTitle(sceneName);
        return pushSmsMapper.queryByTitle(pushSms);
    }

    /**
     * 根据场景信息发送短信方法
     *
     * @author 朱泊阳
     * @date   2019/10/12 10:40
     * @param  objects  需要传入的对象
     * @param  phones  需要发送的手机号
     * @param  pushSms  场景信息,只需要传入id
     */
    @Override
    public void setPushSmsWithTmp(List<Object> objects, List<String> phones, PushSms pushSms) throws Exception {
        if (null != pushSms.getTemId() && null != pushSms.getSignatureId()) {
            //发送短信
            templateService.sendTmpSms(objects, pushSms, phones, null);
        }
    }
}
